﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>View 和 Event 的定义及应用 </title>
    <link media="all"  type="text/css" rel="Stylesheet"  href="Styles/reset.css" />
    <link media="all"  type="text/css" rel="Stylesheet"  href="Styles/960.css" />    
    <link media="all"  type="text/css" rel="Stylesheet"  href="Styles/text.css" />
    <link media="all"  type="text/css" rel="Stylesheet"  href="Styles/layout.css" />
    <link media="all"  type="text/css" rel="Stylesheet"  href="Styles/nav.css" />
    <link media="all"  type="text/css" rel="Stylesheet"  href="Styles/demo.css" />

    <script type="text/javascript" src="Scripts/Libs/jquery-1.8.3.min.js"></script>
     <script type="text/javascript" src="Scripts/Libs/underscore.js"></script>
      <script type="text/javascript" src="Scripts/Libs/backbone.js"></script>
      <script type="text/javascript" src="Scripts/Libs/handlebars.js"></script>
</head>
<body>
   <div class="container_16">
            <div class="grid_16">
				<h2 id="page-heading">Backbone.js Demo —— view-event</h2>
			</div>
            <div class="clear"></div>
            <div class="grid_4 alpha">&nbsp;</div>
            <div class="grid_8">
            <div class="box" >
					<h2>
						注册
					</h2>
					<div style="margin: 0px; position: static; overflow: hidden;"><div id="login-forms" class="block" style="margin: 0px;">
					        <fieldset>
								<legend>注册信息</legend>
                                <p></p>
								<p>
									<label>用户名： </label>
									<input type="text" value="" id="UserName" name="UserName">
								</p>
								<p>
									<label>登陆账号 : </label>
									<input type="text" value="" id="LoginID" name="LoginID">
								</p>
								<p>
									<label>密码： </label>
									<input type="text" value=""  id="PWD" name="PWD">
								</p>
								<p>
									<label>密码确认 : </label>
									<input type="text" value="" id="PWDC" name="PWDC">
								</p>
								<p>
									<label>公司： </label>
									<input type="text" value="" id="Company"   name="Company">
								</p>						
							<p>
									<label>Email 地址： </label>
									<input type="text" value="" id="Email" name="Email">
								</p>
								<input type="submit" class="register-button" id="btnRegister" value="注册">
							</fieldset>
						
					</div></div>
				</div>
            </div>
            <div class="grid_4"></div>
   </div>

      <div class="container_16">
    <div class="box">
            <h2>
						用户列表
					</h2>
            <div id="tables" class="block" style="margin: 0px;">
				
						<table summary="This table includes examples of as many table elements as possible" >
							<caption></caption>
							<colgroup>
								<col class="colA">
								<col class="colB">
								<col class="colB">
                                <col class="colB">
                                <col class="colB">
                                <col class="colC">
							</colgroup>
							<thead>
								<tr>
									<th class="table-head" colspan="6">已注册用户</th>
								</tr>
								<tr>
									<th>ID</th>
									<th>用户名</th>
                                    <th>登陆ID</th>
                                    <th>公司</th>
									<th>Email</th>
                                    <th class="currency">操作</th>
								</tr>
							</thead>
							
							<tbody id="tb_userlist" >
								<tr class="odd">
									<th>Lorem ipsum</th>
									<td>Dolor sit</td>
                                    <td>Dolor sit</td>
                                    <td>Dolor sit</td>
									<td class="currency">$125.00</td>
								</tr>
							
							</tbody>
						</table>
					</div>
    </div>
   </div>

      <script type="text/template" id="handlebars-temp">                
                  
									<th><div> {{ID}}</div>
                                              <div class="edit"><input type="hidden" value="{{ID}}"  name="ed_ID"></div></th>
									<td><div class="display">{{UserName}}</div>
                                              <div class="edit"><input type="text" value="{{UserName}}"  name="ed_UserName"></div></td>
                                    <td><div class="display">{{LoginID}}</div>
                                              <div class="edit"><input type="text" value="{{LoginID}}" name="ed_LoginID"></div></td>
                                    <td><div class="display">{{Company}}</div>
                                              <div class="edit"><input type="text" value="{{Company}}"  name="ed_Company"></div></td>
									<td ><div class="display">{{ Email }}</div>
                                              <div class="edit"><input type="text" value="{{ Email }}"  name="ed_Email"></div></td>
					                <td class="currency">
                                               <div class="display">  <input type="button" class="btnEdit" name="btnEdit" value="编辑">  <input type="button" class="btnDel" name="btnDel" value="删除"></div>
                                              <div class="edit"> <input type="button" class="btnSave" name="btnSave" value="保存">  <input type="button" class="btnCancel" name="btnCancel" value="取消"></div>
                                    </td>
                  
             
   </script>


   <script type="text/javascript">
       $(document).ready(function () {

           // 该Demo 演示 Backbone 中的 Model / Collection /View 定义和 Ajax 交互   实现增删改查
           // 开发：余庆元  
           //==========================
           // 如果服务器不支持 application/json 类型传递的参数解析，就设置为 true 转化为 application/x-www-form-urlencoded
//          Backbone.emulateJSON=true; 
       //  Backbone.emulateHTTP = true;  //如果服务器不支持 RESTful （Get,Post,Put,Delete）解析就设置为 true, 用 POST 发送并自动创建 "_method=Put" URL参数来标识 Put 、Delete

           // 定义一个用户实体
           var User = Backbone.Model.extend({
               urlRoot:'Ajax/Ajax_usercontrol.ashx',//用户提交服务器，采用传统 ashx 一般程序处理文件作交换
                url: function() {
                            var base = this.urlRoot || (this.collection && this.collection.url) || "/";
                            if (this.isNew()) return base;
                            return base + "?ID=" + encodeURIComponent(this.id);
                            },
               initialize: function () { //构造函数，初始化
                   this.on("invalid", function (model, error) {
                       alert(error);
                       return false;
                   });
                    this.on("error", function (model, error) {
                       alert(error);
                       return false;
                   });
               },
//               defaults: { //实体属性定义
//                   ID: '',
//                   UserName: '',
//                   LoginID: '',
//                   PWD: '',
//                   Company: '',
//                   Email: ''
//               },
               idAttribute:"ID",  //主键， 设置之后程序才能识别采用 那种 RESTful 发送到服务器
               //规则校验
               validate: function (attributes) {
                   if (attributes.UserName == '') {
                       return "用户名不能为空！";
                   };

                   if (attributes.LoginID == '') {
                       return "登录账号不能为空！"
                   };

                   if (attributes.PWD == '') {
                       return "密码不能为空！"
                   }
               },
               //自定义方法
               register: function () {
                   this.save(); //保存实体 save 为backbone自带方法。
               }

           });

           //===================
           //定义 user collection 

           var userlist = Backbone.Collection.extend({
               model: User,
               url: 'Ajax/Ajax_userlist.ashx', //服务器响应地址
               initialize: function () { //构造函数，初始化

               },
           });

          var newList = new userlist;        //创建一个新集合对象


          //====================
           //定义视图 View

           var UserView=Backbone.View.extend({
                tagName:"tr",
                template:Handlebars.compile($('#handlebars-temp').html()) , // 使用 Handlebars 模板
                initialize:function(){
                        this.model.bind("change",this.render,this);
                        this.model.bind("destroy",this.remove,this);
                },
                 events:{
                    'click .btnEdit' : 'edit',
                    'click .btnSave' : 'close',
                    'click .btnDel':'clear',
                    'click .btnCancel':'cancel',
                    'dblclick td':'edit',
                },
                edit:function(e){
                        $(this.el).addClass('editing');
                },
                close:function(e){
                        
                       // var tr=$(e.currentTarget).parent().parent().parent();

                       // alert(tr.find("input[name='ed_ID']").val());

                        var _username= $(this.el).find("input[name='ed_UserName']").val();
                        var _loginid= $(this.el).find("input[name='ed_LoginID']").val();
                        var _company= $(this.el).find("input[name='ed_Company']").val();
                        var _email= $(this.el).find("input[name='ed_Email']").val();
                        this.model.save({UserName: _username,
                                                       LoginID: _loginid,
                                                       Company: _company,
                                                       Email: _email},
                                                  {success: function (model, response) {
                                                        alert(response);
                                                  }, // all good
                                                  error: function (model, xhr) {
                                                    alert(xhr);
                                                  } // xhr error
                                                  });

                        if (!this.model.validationError) {
                              // validate error(s) accessible in model.validationError
                                $(this.el).removeClass('editing');
                            }
                        
                       
                },
                clear:function(){
                        this.model.destroy();
                },
                remove:function(e){
                     //var tr=$(e.currentTarget).parent().parent().parent();
                     $(this.el).remove();
                },
                cancel:function(e){
                    var tr= $(this.el);
                    tr.find("input[name='ed_UserName']").val(this.model.get("UserName"));
                    tr.find("input[name='ed_LoginID']").val(this.model.get("LoginID"));
                    tr.find("input[name='ed_Company']").val(this.model.get("Company"));
                    tr.find("input[name='ed_Email']").val(this.model.get("Email"));
                    tr.removeClass('editing');

                },
                render:function(){
                     $(this.el).html(this.template(this.model.toJSON()));
                     return this;
                }

           });

             var AppView = Backbone.View.extend({
               el: "body",              
               initialize: function () {
                    newList.bind("add",this.addOne,this);
                    newList.bind("reset", this.addAll,this); 
                    newList.fetch();
               },
               events:{
                    "click  #btnRegister":"create"
               },
               create:function(e){
                      var regUser = new User;

//                         regUser.sync=function(method, model) {
//                              alert(method + ": " + model.url);
//                        };

                       if ($("#PWD").val() != $("#PWDC").val()) {
                           alert("密码确认不一致！");
                           return false;
                       } else {

                             var _username=$("#UserName").val();
                            var _loginid=$("#LoginID").val();
                            var _pwd=$("#PWD").val();
                             var _company=$("#Company").val();
                            var _email=$("#Email").val();
                        
                            if(regUser.set({ UserName:_username ,
                                    LoginID:_loginid ,
                                    PWD: _pwd,
                                    Company:_company,
                                    Email:_email
                            },{validate:true})){
                            // 设置 { wait: true } 将会在服务器返回正确之后才添加对应视图。
                             newList.create(regUser,{ wait: true });  

//                             ,{success: function (model, response) {
//                                                        alert(response);
//                                                  }, // all good
//                                                  error: function (model, xhr) {
//                                                    alert(xhr);
//                                                  } // xhr error
//                                                  }

                            }
                       };
               },
               addOne:function(user){             
        	        var view = new UserView({model:user});
        	        $("#tb_userlist").append(view.render().el);
                },
                addAll : function(){
                  $("#tb_userlist").empty();
        	     newList.each(this.addOne);

                 //尝试采用下面方法绑定，结果对象的对应事件都没绑定。
//                   var trlist=""
//                  // var obj={};
//                   newList.each(function (user) {
//                         var view = new UserView({model:user});
//                          trlist+=view.render().el.outerHTML;
//                         
//                   });
//                  $("#tb_userlist").html(trlist);

                }


           });

            var view=new AppView();



       });

   </script>

</body>
</html>
